package com.xiyou.weblog.jwt.handler;

import com.xiyou.weblog.common.enums.ResponseCodeEnum;
import com.xiyou.weblog.common.utils.Response;
import com.xiyou.weblog.jwt.utils.ResultUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author xiyou
 * @description 用户未登录访问受保护的资源
 */
@Slf4j
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.warn("用户未登录访问受保护的资源: ", authException);
        if (authException instanceof InsufficientAuthenticationException) {
            ResultUtil.fail(response, HttpStatus.UNAUTHORIZED.value(), Response.fail(ResponseCodeEnum.UNAUTHORIZED));
        }
        ResultUtil.fail(response,HttpStatus.UNAUTHORIZED.value(), Response.fail(authException.getMessage()));
//        主要用于处理下图中，红框标注的，当校验 Token 异常时，捕获之，并主动调用 commence() 方法

        /**
         * tokenAuthenticationFilter的方法：
         *                 try {
         *                     jwtTokenHelper.validateToken(token);
         *                 } catch (SignatureException | MalformedJwtException | UnsupportedJwtException | IllegalArgumentException e) {
         *                     // 抛出异常，统一让 AuthenticationEntryPoint 处理响应参数
         *                     authenticationEntryPoint.commence(request,response,new AuthenticationServiceException("Token 不可用"));
         *                     return;
         *                 }catch (ExpiredJwtException e) {
         *                     authenticationEntryPoint.commence(request,response,new AuthenticationServiceException("Token 已失效"));
         *                     return;
         *                 }
         */
    }
}
